package com.suixinsanren.design.state.demo.demo07;

public class GumballMachine {

    private State state;
    private int numberGumball;

    private State hasQuarterState;
    private State noQuarterState;
    private State soldOutState;
    private State soldState;

    public GumballMachine(int numberGumball) {
        this.numberGumball = numberGumball;
        this.hasQuarterState = new HashQuarterState(this);
        this.noQuarterState = new NoQuarterState(this);
        this.soldOutState = new SoldOutState(this);
        this.soldState = new SoldState(this);
        updateStateByNumberGumball();
    }

    public void insertQuarter() {
        state.insertQuarter();
    }

    public void ejectQuarter() {
        state.ejectQuarter();
    }

    public void turnCrank() {
        state.turnCrank();
        state.dispense();
    }

    public void release() {
        if (numberGumball > 0) {
            numberGumball--;
            System.out.println("恭喜您获得一颗糖果");
        }
        updateStateByNumberGumball();
    }

    private void updateStateByNumberGumball() {
        state = numberGumball > 0 ? noQuarterState : soldOutState;
    }

    public void refill(int numberGumball) {
        if (numberGumball > 0) {
            this.numberGumball += numberGumball;
            updateStateByNumberGumball();
        }
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public State getHasQuarterState() {
        return hasQuarterState;
    }

    public void setHasQuarterState(State hasQuarterState) {
        this.hasQuarterState = hasQuarterState;
    }

    public State getNoQuarterState() {
        return noQuarterState;
    }

    public void setNoQuarterState(State noQuarterState) {
        this.noQuarterState = noQuarterState;
    }

    public State getSoldOutState() {
        return soldOutState;
    }

    public void setSoldOutState(State soldOutState) {
        this.soldOutState = soldOutState;
    }

    public State getSoldState() {
        return soldState;
    }

    public void setSoldState(State soldState) {
        this.soldState = soldState;
    }

    public int getNumberGumball() {
        return numberGumball;
    }

    @Override
    public String toString() {
        return "糖果机器 {" +
                "当前状态=" + state +
                ", 当前糖果数量=" + numberGumball +
                '}';
    }
}
